<template>
  <div class="register-container">
    <div class="register-card">
      <h2>注册账号</h2>
      
      <form @submit.prevent="handleRegister" class="register-form" @keypress="handleKeyPress">
        <div class="form-group">
          <input 
            v-model="registerForm.username" 
            type="text" 
            placeholder="用户名（3-20位，字母数字下划线）" 
            required
            :class="{ 'valid': usernameValid && registerForm.username, 'invalid': registerForm.username && !usernameValid }"
            @blur="checkUsername"
          >
          <div v-if="registerForm.username && !usernameValid" class="field-error">
            用户名长度至少3位，只能包含字母、数字和下划线
          </div>
        </div>
        
        <div class="form-group">
          <input 
            v-model="registerForm.email" 
            type="email" 
            placeholder="邮箱地址" 
            required
            :class="{ 'valid': emailValid && registerForm.email, 'invalid': registerForm.email && !emailValid }"
            @blur="checkEmail"
          >
          <div v-if="registerForm.email && !emailValid" class="field-error">
            请输入有效的邮箱地址
          </div>
        </div>
        
        <div class="form-group">
          <input 
            v-model="registerForm.nickname" 
            type="text" 
            placeholder="昵称（可选，默认为用户名）" 
          >
        </div>
        
        <div class="form-group password-group">
          <input 
            v-model="registerForm.password" 
            :type="showPassword ? 'text' : 'password'" 
            placeholder="密码（至少6位）" 
            required
            :class="{ 'valid': passwordValid && registerForm.password, 'invalid': registerForm.password && !passwordValid }"
          >
          <button 
            type="button" 
            class="password-toggle"
            @click="togglePasswordVisibility"
            :title="showPassword ? '隐藏密码' : '显示密码'"
          >
            {{ showPassword ? '👁️' : '👁️‍🗨️' }}
          </button>
          <div v-if="registerForm.password && !passwordValid" class="field-error">
            密码长度不能少于6位
          </div>
        </div>
        
        <div class="form-group password-group">
          <input 
            v-model="registerForm.confirmPassword" 
            :type="showConfirmPassword ? 'text' : 'password'" 
            placeholder="确认密码" 
            required
            :class="{ 'valid': passwordMatch && registerForm.confirmPassword, 'invalid': registerForm.confirmPassword && !passwordMatch }"
          >
          <button 
            type="button" 
            class="password-toggle"
            @click="toggleConfirmPasswordVisibility"
            :title="showConfirmPassword ? '隐藏密码' : '显示密码'"
          >
            {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
          </button>
          <div v-if="registerForm.confirmPassword && !passwordMatch" class="field-error">
            两次输入的密码不一致
          </div>
        </div>
        
        <div class="form-group checkbox-group">
          <label class="checkbox-label">
            <input 
              v-model="registerForm.agreeToTerms" 
              type="checkbox" 
              required
            >
            <span class="checkmark"></span>
            我已阅读并同意
            <a href="#" class="link">《用户协议》</a>
            和
            <a href="#" class="link">《隐私政策》</a>
          </label>
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <button 
          type="submit" 
          class="register-btn"
          :disabled="isLoading || !formValid"
          :class="{ 'disabled': !formValid }"
        >
          {{ isLoading ? '注册中...' : '注册' }}
        </button>
      </form>
      
      <div class="login-link">
        <span>已有账号？</span>
        <a href="#" @click.prevent="goToLogin" class="link">立即登录</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router';

// 初始化store和router
const userStore = useUserStore();
const router = useRouter();

    const registerForm = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      nickname: '',
      agreeToTerms: false
    });

    const isLoading = ref(false);
    const errorMessage = ref('');
    const showPassword = ref(false);
    const showConfirmPassword = ref(false);
    const step = ref(1); // 注册步骤：1-基本信息，2-验证邮箱，3-完成
    const verificationCode = ref('');
    const emailSent = ref(false);
    const countdown = ref(0);

// 表单验证
const usernameValid = computed(() => {
  return registerForm.username.length >= 3 && /^[a-zA-Z0-9_]+$/.test(registerForm.username);
});

const emailValid = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(registerForm.email);
});

const passwordValid = computed(() => {
  return registerForm.password.length >= 6;
});

const passwordMatch = computed(() => {
  return registerForm.password === registerForm.confirmPassword && registerForm.confirmPassword.length > 0;
});

const formValid = computed(() => {
  return usernameValid.value && emailValid.value && passwordValid.value && passwordMatch.value && registerForm.agreeToTerms;
});

const validateForm = () => {
  if (!registerForm.username.trim()) {
    errorMessage.value = '请输入用户名';
    return false;
  }
  
  if (!usernameValid.value) {
    errorMessage.value = '用户名长度至少3位，只能包含字母、数字和下划线';
    return false;
  }

  if (!registerForm.email.trim()) {
    errorMessage.value = '请输入邮箱地址';
    return false;
  }
  
  if (!emailValid.value) {
    errorMessage.value = '请输入有效的邮箱地址';
    return false;
  }

  if (!registerForm.password) {
    errorMessage.value = '请输入密码';
    return false;
  }
  
  if (!passwordValid.value) {
    errorMessage.value = '密码长度不能少于6位';
    return false;
  }

  if (!registerForm.confirmPassword) {
    errorMessage.value = '请确认密码';
    return false;
  }
  
  if (!passwordMatch.value) {
    errorMessage.value = '两次输入的密码不一致';
    return false;
  }

  if (!registerForm.agreeToTerms) {
    errorMessage.value = '请同意用户协议和隐私政策';
    return false;
  }

  return true;
};

const handleRegister = async () => {
  errorMessage.value = '';
  
  if (!validateForm()) {
    return;
  }

  isLoading.value = true;

  try {
    const success = await userStore.register({
      username: registerForm.username.trim(),
      email: registerForm.email.trim(),
      password: registerForm.password,
      nickname: registerForm.nickname.trim() || registerForm.username.trim()
    });

    if (success) {
      // 注册成功，可以选择直接登录或跳转到登录页
      alert('注册成功！请登录');
      router.push('/login');
    }
  } catch (error) {
    console.error('注册失败:', error);
    // 根据错误类型显示不同的错误信息
    if (error.response) {
      switch (error.response.status) {
        case 409:
          errorMessage.value = '用户名或邮箱已存在';
          break;
        case 400:
          errorMessage.value = error.response.data?.message || '注册信息有误，请检查后重试';
          break;
        case 429:
          errorMessage.value = '注册请求过于频繁，请稍后再试';
          break;
        default:
          errorMessage.value = error.response.data?.message || '注册失败，请重试';
      }
    } else if (error.code === 'NETWORK_ERROR') {
      errorMessage.value = '网络连接失败，请检查网络设置';
    } else {
      errorMessage.value = '注册失败，请重试';
    }
  } finally {
    isLoading.value = false;
  }
};

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

const goToLogin = () => {
  router.push('/login');
};

// 检查用户名是否可用
const checkUsername = async () => {
  if (!registerForm.username.trim() || !usernameValid.value) {
    return;
  }
  
  try {
    // 这里可以调用API检查用户名是否可用
    // const available = await userStore.checkUsernameAvailable(registerForm.username);
    console.log('检查用户名可用性:', registerForm.username);
  } catch (error) {
    console.error('检查用户名失败:', error);
  }
};

// 检查邮箱是否可用
const checkEmail = async () => {
  if (!registerForm.email.trim() || !emailValid.value) {
    return;
  }
  
  try {
    // 这里可以调用API检查邮箱是否可用
    // const available = await userStore.checkEmailAvailable(registerForm.email);
    console.log('检查邮箱可用性:', registerForm.email);
  } catch (error) {
    console.error('检查邮箱失败:', error);
  }
};

// 处理回车键
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && formValid.value) {
    handleRegister();
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  position: relative;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #fcc;
  text-align: center;
  font-size: 14px;
}

input {
  width: 100%;
  padding: 15px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: #fff;
  box-sizing: border-box;
}

input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

input.valid {
  border-color: #27ae60;
  background-color: #f8fff9;
}

input.invalid {
  border-color: #e74c3c;
  background-color: #fff8f8;
}

.password-group {
  position: relative;
}

.password-group input {
  padding-right: 50px;
}

.password-toggle {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  color: #666;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.password-toggle:hover {
  background-color: #f0f0f0;
  color: #333;
}

.field-error {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 5px;
}

.checkbox-group {
  margin: 10px 0;
}

.checkbox-label {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  font-size: 14px;
  color: #555;
  line-height: 1.4;
}

.checkbox-label input[type="checkbox"] {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
  margin-top: 2px;
  flex-shrink: 0;
  position: relative;
  transition: all 0.2s ease;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark {
  background-color: #667eea;
  border-color: #667eea;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.link:hover {
  text-decoration: underline;
}

.register-btn {
  padding: 15px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}

.register-btn:disabled,
.register-btn.disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
}

.login-link a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .register-card {
    margin: 20px;
    padding: 30px 20px;
  }
  
  h2 {
    font-size: 24px;
  }
}
</style>